import React, { FC, MouseEvent } from 'react'
import classNames from 'classnames'
import styles from './EditCanvas.module.scss'
import { Spin } from 'antd'
import { useDispatch } from 'react-redux'
import { ComponentInfoType, changeSelectedId } from '../../../store/componentsReducer/index'
import useGetComponentInfo from '../../../hooks/useGetComponentInfo'
import { getComponentConfByType } from '../../../layouts/QuestionComponents/index'
type PropsType = {
  loading: boolean
}
function getComponentConfByTypeHandler(compontInfo: ComponentInfoType) {
  const { type = '', props } = compontInfo
  const conponentConf = getComponentConfByType(type)
  if (!conponentConf) return null
  const { Component } = conponentConf
  return <Component {...props} />
}
const EditCanvas: FC<PropsType> = ({ loading }) => {
  const dispatch = useDispatch()

  console.log('componentList', useGetComponentInfo())
  const { componentList = [], selectedId } = useGetComponentInfo()
  console.log('componentsList:------', componentList)
  function handleClick(event: MouseEvent, id: string) {
    event.stopPropagation() // 阻止冒泡
    dispatch(changeSelectedId(id))
  }

  if (loading) {
    return (
      <div style={{ textAlign: 'center' }}>
        <Spin />
      </div>
    )
  }
  return (
    <div className={styles.canvas}>
      {componentList.map(c => {
        const { fe_id } = c
        const wrapperDefaultClassName = styles['component-wrapper']
        const selectedClassName = styles.selected
        const lockedClassName = styles.locked
        const wrapperClassName = classNames({
          [wrapperDefaultClassName]: true,
          [selectedClassName]: fe_id === selectedId,
        })

        return (
          <div
            key={fe_id}
            className={wrapperClassName}
            onClick={event => {
              handleClick(event, fe_id)
            }}
          >
            <div className={styles.components}>{getComponentConfByTypeHandler(c)}</div>
          </div>
        )
      })}
    </div>
  )
}
export default EditCanvas
